package top.hypnos.bigdata.filesystem.record;

import java.io.IOException;
import java.io.OutputStream;

public class ObjectOutputStreamImpl implements ObjectOutputStream {

    private final OutputStream out;

    public ObjectOutputStreamImpl(OutputStream out) {
        this.out = out;
    }

    @Override
    public void writeInt(int data) throws IOException {
        final var bytes = new byte[4];
        bytes[0] = (byte) ((data >> 3) & 0xFF);
        bytes[1] = (byte) ((data >> 2) & 0xFF);
        bytes[2] = (byte) ((data >> 1) & 0xFF);
        bytes[3] = (byte) (data & 0xFF);
        out.write(bytes);
    }

    @Override
    public void writeBytes(byte[] data) throws IOException {
        if (data == null) {
            writeInt(0);
            return;
        }
        final var length = data.length;
        writeInt(length);
        out.write(data);
    }
}
